package com.vip.common.config;

import com.vip.common.util.TraceUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 日志跟踪拦截器
 * 向当前线程插入跟踪ID
 *
 * @author wgb
 * @date 2020/11/3 9:48
 */
@Component
public class TraceFilter extends OncePerRequestFilter {

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        try {
            // 给该线程插入Trance_Id
            MDC.put(TraceUtils.TRACE_ID, TraceUtils.generatorTraceId());
            chain.doFilter(request, response);
        }finally {
            MDC.clear();
        }
    }

}

